package project.gc.com.myapplication.glide;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;

import java.lang.ref.SoftReference;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import project.gc.com.myapplication.R;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

/**
 * Created by apple on 16/12/19.
 */

public class GlideUtils {


    static RequestListener listener = new RequestListener() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            return false;
        }

    };


    public static void loadGifImage(Context mContext, Object path, ImageView mImageView) {
        SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .priority(Priority.HIGH)
                .placeholder(R.mipmap.ic_launcher)
                .diskCacheStrategy(DiskCacheStrategy.NONE);
        Glide.with(mContext)
                .asGif()
                .apply(options)
                .load(buildGlideUrl(path))
//                .listener(listener)
                .into(imageView.get());
    }


    /**
     * 默认加载
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageViewNoLoading(Context mContext, Object path, ImageView mImageView) {
        SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.ic_launcher)
                .centerCrop()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(mContext)
                .load(buildGlideUrl(path))
                .apply(options)
//                .listener(listener)
                .into(imageView.get());
    }

    /**
     * 默认加载
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageView(Context mContext, Object path, ImageView mImageView) {
        try {
            mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            RequestOptions options = new RequestOptions()
//                    .centerCrop()
                    .skipMemoryCache(true)
                    .override(imageView.get().getWidth(), imageView.get().getHeight())
                    .placeholder(R.mipmap.ic_launcher)
                    .error(R.mipmap.ic_launcher)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
            Glide.with(mContext)
                    .asBitmap()
                    .load(buildGlideUrl(path))
                    .apply(options)
//                    .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 默认加载
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageViewCache(Context mContext, Object path, ImageView mImageView) {
        try {
//            mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            RequestOptions options = new RequestOptions()
//                    .centerCrop()
                    .skipMemoryCache(false)
//                    .override(imageView.get().getWidth(), imageView.get().getHeight())
//                    .placeholder(R.mipmap.ic_launcher)
//                    .error(R.mipmap.ic_launcher)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
            Glide.with(mContext)
                    .asBitmap()
                    .load(buildGlideUrl(path))
                    .apply(options)
//                    .listener(listener)
                    .into(mImageView);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 默认加载 设置默认加载图
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageView(Context mContext, Object path, ImageView mImageView, @DrawableRes int defaultRes) {
        if (defaultRes <= 0) {
            defaultRes = R.mipmap.ic_launcher;
        }
        try {
            mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            RequestOptions options = new RequestOptions()
//                    .centerCrop()
                    .skipMemoryCache(true)
                    .override(imageView.get().getWidth(), imageView.get().getHeight())
                    .placeholder(defaultRes)
                    .error(defaultRes)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
            Glide.with(mContext)
                    .asBitmap()
                    .load(buildGlideUrl(path))
                    .apply(options)
//                    .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }


    /**
     * 默认加载
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageView(Context mContext, Object path, final ImageView mImageView, final OnImageLoadListener listener) {

        try {
            mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            final SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                @Override
                public void onStart() {
                    super.onStart();
                    if (listener != null)
                        listener.onStart();
                }

                @Override
                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                    imageView.get().setImageDrawable(resource);
                    if (listener != null)
                        listener.onFinished(resource);
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    super.onLoadFailed(errorDrawable);
                    if (listener != null)
                        listener.onError();

                }
            };
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
            Glide.with(mContext)
                    .load(buildGlideUrl(path))
                    .apply(options)
                    .into(simpleTarget);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 默认加载
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageViewNoScale(Context mContext, Object path, final ImageView mImageView, final OnImageLoadListener listener) {

        try {
            final SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                @Override
                public void onStart() {
                    super.onStart();
                    if (listener != null)
                        listener.onStart();
                }

                @Override
                public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                    imageView.get().setImageDrawable(resource);
                    if (listener != null)
                        listener.onFinished(resource);
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    super.onLoadFailed(errorDrawable);
                    if (listener != null)
                        listener.onError();

                }
            };
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
            Glide.with(mContext)
                    .load(buildGlideUrl(path))
                    .apply(options)
                    .into(simpleTarget);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 默认加载
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadImageViewNoScale(Context mContext, Object path, final ImageView mImageView) {


        try {
            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            RequestOptions options = new RequestOptions()
                    .skipMemoryCache(true)
                    .override(imageView.get().getWidth(), imageView.get().getHeight())
                    .placeholder(R.mipmap.ic_launcher)
                    .error(R.mipmap.ic_launcher)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
            Glide.with(mContext)
                    .asBitmap()
                    .load(buildGlideUrl(path))
                    .apply(options)
//                    .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }


    //图片加载监听
    public interface OnImageLoadListener {
        void onFinished(Drawable resource);

        void onError();

        void onStart();
    }

    /**
     * 加载圆形图
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadCircleImageView(Context mContext, Object path, ImageView mImageView, @DrawableRes int defId) {
        SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
        try {
//            XLog.d("loadCircleImageView", path.toString());
            RequestOptions options = new RequestOptions()
                    .circleCrop()
                    .placeholder(defId)
                    .error(defId)
                    .priority(Priority.NORMAL)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
            Glide.with(mContext)
                    .asBitmap()
                    .load(buildGlideUrl(path))
                    .apply(options)
                    .thumbnail(Glide.with(mContext)
                            .asBitmap().load(defId).apply(options))
//                    .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载圆形图
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadCircleImageView(Context mContext, Object path, ImageView mImageView) {
        loadCircleImageView(mContext, path, mImageView, R.mipmap.ic_launcher);
    }

//    /**
//     * 加载圆角图
//     *
//     * @param mContext   上下文
//     * @param path       路径
//     * @param mImageView 图片的控件
//     */
//    public static void loadRoundedImageView(Context mContext, Object path, ImageView mImageView) {
//        try {
//            if (mImageView != null) {
//                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
//            } else {
//                return;
//            }
//            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
//            int radius = mContext.getResources().getDimensionPixelOffset(R.dimen.x8);
//
//            MultiTransformation multi = new MultiTransformation(
//                    new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL));
//
//
//            RequestOptions options = bitmapTransform(multi)
//                    .placeholder(R.mipmap.ic_launcher)
//                    .skipMemoryCache(true)
//                    .override(imageView.get().getWidth(),imageView.get().getHeight())
//                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
//            Glide.with(mContext)
//                    .load(buildGlideUrl(path))
//                    .apply(options)
//                    .into(imageView.get());
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        }
//
//    }

//    /**
//     * 加载圆角图
//     *
//     * @param mContext   上下文
//     * @param path       路径
//     * @param mImageView 图片的控件
//     */
//    public static void loadRoundedImageView(Context mContext, Object path, int radius, ImageView mImageView) {
//        try {
//            if (mImageView != null) {
//                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
//            } else {
//                return;
//            }
//            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
////            Glide.with(mContext)
////                    .load(path)
////                    .apply(bitmapTransform(new RoundedCornersTransformation(45, 0,
////                            RoundedCornersTransformation.CornerType.BOTTOM)))
////                    .into(mImageView);
//
//            MultiTransformation multi = new MultiTransformation(
//                    new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL));
//
//
//            RequestOptions options = bitmapTransform(multi)
//                    .placeholder(R.mipmap.ic_launcher)
//                    .skipMemoryCache(false)
//                    .diskCacheStrategy(DiskCacheStrategy.ALL);
//            Glide.with(mContext)
//                    .load(buildGlideUrl(path))
//                    .apply(options)
////                    .listener(listener)
//                    .into(imageView.get());
//        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
//        }
//
//    }

    /**
     * 加载圆角图
     *
     * @param mContext   上下文
     * @param path       路径
     * @param mImageView 图片的控件
     */
    public static void loadRoundedImageView(Context mContext, Object path, RoundedCornersTransformation.CornerType cornerType, ImageView mImageView) {
        try {
            if (mImageView != null) {
                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            } else {
                return;
            }
            int radius = 12;
            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
//            Glide.with(mContext)
//                    .load(path)
//                    .apply(bitmapTransform(new RoundedCornersTransformation(45, 0,
//                            RoundedCornersTransformation.CornerType.BOTTOM)))
//                    .into(mImageView);

            MultiTransformation multi = new MultiTransformation(
                    new RoundedCornersTransformation(radius, 0, cornerType));


            RequestOptions options = bitmapTransform(multi)
                    .placeholder(R.mipmap.ic_launcher)
                    .error(R.mipmap.ic_launcher)
                    .skipMemoryCache(false)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
            Glide.with(mContext)
                    .load(buildGlideUrl(path))
                    .apply(options)
//                    .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 加载指定大小
     *
     * @param mContext   上下文
     * @param path       路径
     * @param width      图片的宽
     * @param height     图片的高
     * @param mImageView 图片的控件
     */
    public static void loadImageViewSize(Context mContext, Object path, int width, int height, ImageView mImageView) {

        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.ic_launcher)
                .centerCrop()
                .skipMemoryCache(true)
                .override(width, height)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE);

        Glide.with(mContext).load(buildGlideUrl(path)).apply(options).into(mImageView);
    }

    /**
     * 设置加载中以及加载失败图片
     *
     * @param mContext       上下文
     * @param path           图片的路径
     * @param mImageView     图片的控件
     * @param lodingImage    加载图
     * @param errorImageView 加载失败图
     */
    public static void loadImageViewLoding(Context mContext, Object path, ImageView mImageView, int lodingImage, int errorImageView) {
        try {
            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            RequestOptions options = new RequestOptions()
                    .placeholder(lodingImage)
                    .centerCrop()
                    .priority(Priority.HIGH)
                    .error(errorImageView)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
            Glide.with(mContext)
                    .load(buildGlideUrl(path))
                    .apply(options)
//                .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置加载中以及加载失败图片
     *
     * @param mContext       上下文
     * @param path           图片的路径
     * @param mImageView     图片的控件
     * @param lodingImage    加载图
     * @param errorImageView 加载失败图
     */
    public static void loadImageViewLoding(Fragment mContext, String path, ImageView mImageView, int lodingImage, int errorImageView) {
        RequestOptions options = new RequestOptions()
                .placeholder(lodingImage)
                .centerCrop()
                .priority(Priority.HIGH)
                .error(errorImageView)
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(mContext)
                .load(buildGlideUrl(path))
//                .listener(listener)
                .into(mImageView);
    }


    /**
     * 策略解说：
     * <p>
     * all:缓存源资源和转换后的资源
     * <p>
     * none:不作任何磁盘缓存
     * <p>
     * source:缓存源资源
     * <p>
     * result：缓存转换后的资源
     */


    /**
     * 设置缩略图支持
     * 会先加载缩略图
     *
     * @param mContext   上下文
     * @param path       图片的路径
     * @param mImageView 图片的控件
     */
    public static void loadImageViewThumbnail(Context mContext, String path, ImageView mImageView) {
        Glide.with(mContext).load(path).thumbnail(0.1f).into(mImageView);
    }

//    /**
//     * 设置监听请求接口
//     * 设置监听的用处 可以用于监控请求发生错误来源，以及图片来源 是内存还是磁盘
//     *
//     * @param mContext       上下文
//     * @param path           图片的路径
//     * @param mImageView     图片的控件
//     * @param requstlistener 请求监听
//     */
//    public static void loadImageViewListener(Context mContext, String path, ImageView mImageView, RequestListener<String, GlideDrawable> requstlistener) {
//        Glide.with(mContext).load(path).listener(requstlistener).into(mImageView);
//    }
//
//    //
//
//    //
//
//    /**
//     * 设置要加载的内容
//     * 项目中有很多需要先下载图片然后再做一些合成的功能，比如项目中出现的图文混排
//     *
//     * @param mContext     上下文
//     * @param path         图片的路径
//     * @param simpleTarget
//     */
//    public static void loadImageViewContent(Context mContext, String path, SimpleTarget<GlideDrawable> simpleTarget) {
//        Glide.with(mContext).load(path).centerCrop().into(simpleTarget);
//    }

    /**
     * 清理磁盘缓存
     * 理磁盘缓存 需要在子线程中执行
     *
     * @param mContext 上下文
     */
    public static void GuideClearDiskCache(Context mContext) {
        Glide.get(mContext).clearDiskCache();
    }

    /**
     * 清理内存缓存
     * 清理内存缓存  可以在UI主线程中进行
     *
     * @param mContext
     */
    public static void GuideClearMemory(Context mContext) {
        Glide.get(mContext).clearMemory();
    }

    /**
     * 添加防盗链信息
     *
     * @param url
     * @return
     */
    private static Object buildGlideUrl(Object url) {
//        if (url != null && TextUtils.isEmpty(url.toString())) {
//            return null;
//        } else if (url != null && (url.toString().contains("http://") || url.toString().contains("https://"))) {
//            return new GlideUrl(url.toString(), new LazyHeaders.Builder().addHeader("Referer", Constants.IMAGE_REFERER).build());
//        } else {
//            return url;
//        }
        return url;
    }

    /**
     * 加载视频第一帧
     *
     * @param mContext
     * @param bytes
     * @param mImageView
     */
    public static void loadVideoImageView(Context mContext, Bitmap bytes, ImageView mImageView) {
        try {
            SoftReference<ImageView> imageView = new SoftReference<>(mImageView);
            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .skipMemoryCache(true)
                    .placeholder(R.mipmap.ic_launcher)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
            Glide.with(mContext)
                    .load(bytes)
                    .apply(options)
//                    .listener(listener)
                    .into(imageView.get());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

    }
}
